package us.kg.kotoriforest.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用来记录日志的过滤器
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/9
 */
@WebFilter({"/filter/servlet1"})
public class LoggingFilter implements Filter {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 请求之后，放行之前的代码
//        servletResponse.setCharacterEncoding("UTF-8");
//        servletResponse.setContentType("text/html;charset=utf-8");
//        servletResponse.getWriter().print("Before doFilter"); // 可以向 response 中写入数据


        // 参数父转子
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取被请求资源的 uri
        String URI = request.getRequestURI();
        // 获取当前时间
        String now = FORMATTER.format(LocalDateTime.now());

        String output = String.format("[%s]资源在[%s]时刻被访问%n\n", URI, now);
        System.out.println(output);
        // 获取当前时间戳
        long begin = System.currentTimeMillis();

        // 将请求进行放行
        filterChain.doFilter(servletRequest, servletResponse);
        now = FORMATTER.format(LocalDateTime.now());

        long end = System.currentTimeMillis();
        output = String.format("[%s]资源在[%s]时刻结束被访问,共花费[%d]ms%n\n", URI, now, end - begin);
        System.out.println(output);

        // 放行之后，响应之前的代码
//        servletResponse.getWriter().print("After doFilter"); // 不可以向 response 中写入数据
    }
}
